package br.com.remedioCerto.preference;

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;

public class EstoquePreference extends DialogPreference {

	private int ultimaHora = 0;
    private int ultimoMinuto = 0;
    private TimePicker timePicker = null;
    
	public EstoquePreference(Context context) {
		this(context, null);
	}
	
	public EstoquePreference(Context contexto, AttributeSet atributos) {
		this(contexto, atributos, 0);
	}
	
	public EstoquePreference(Context contexto, AttributeSet atributos, int estilo) {
		super(contexto, atributos, estilo);
		setPositiveButtonText("Definir");
        setNegativeButtonText("Cancelar");
	}

	public static int getHora(String tempo) {
		String[] fragmentos = tempo.split(":");
		return Integer.parseInt(fragmentos[0]);
	}
	
	public static int getMinuto(String tempo) {
		String[] fragmentos = tempo.split(":");
		return Integer.parseInt(fragmentos[1]);
	}
	
	
	@Override
	protected View onCreateDialogView() {
        this.timePicker = new TimePicker(getContext());
		return this.timePicker;
	}
	
    @Override
    protected void onBindDialogView(View view) {
        super.onBindDialogView(view);
 
        this.timePicker.setCurrentHour(ultimaHora);
        this.timePicker.setCurrentMinute(ultimoMinuto);
    }
    
	@Override
	protected void onSetInitialValue(boolean restorePersistedValue,	Object defaultValue) {
		String tempo = null;
		
		if (restorePersistedValue) {
			if (defaultValue == null) {
				tempo = getPersistedString("00:00");
			} else {
				tempo = getPersistedString(defaultValue.toString());
			}
		} else {
			tempo = defaultValue.toString();
		}
		
		ultimaHora = getHora(tempo);
		ultimoMinuto = getMinuto(tempo);
	}
    
	@Override
	protected Object onGetDefaultValue(TypedArray a, int index) {
		return a.getString(index);
	}
	
    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
 
        if (positiveResult) {
            this.ultimaHora = this.timePicker.getCurrentHour();
            this.ultimoMinuto = this.timePicker.getCurrentMinute();
 
            String tempo = String.valueOf(ultimaHora) + ":" + String.valueOf(ultimoMinuto);
 
            if (callChangeListener(tempo)) {
                persistString(tempo);
            }
        }
    }
 
}
